package com.rw;

import com.rw.pojo.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMybatis {
    Logger logger = LoggerFactory.getLogger(TestMybatis.class);

    /**
     * 获取session的写法
     */
    @Test
    public void getSession() throws IOException {
        //读取mybatis配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybaits.xml");
        //获得SqlSession的工厂类
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //创建SqlSession
        SqlSession sqlSession = factory.openSession();
        //调用查询的方法
        List<Account> list = sqlSession.selectList("ab.cd.AccountMapper.selectAll");
        System.out.println(list);
        sqlSession.close();
    }


    @Test
    public void testSelectById() throws IOException {
        //读取mybatis配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybaits.xml");
        //获得SqlSession的工厂类
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //创建SqlSession
        SqlSession sqlSession = factory.openSession();
        //调用查询方法
        Account account = sqlSession.selectOne("com.rw.mapper.AccountMapper.selectById", 10);
        System.out.println(account);
        sqlSession.close();
        Assert.assertNotNull(account);
    }

    @Test
    public void testSaveData() throws IOException {
        //读取mybatis配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybaits.xml");
        //获得SqlSession的工厂类
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //创建SqlSession
        SqlSession sqlSession = factory.openSession();
        //调用查询方法
        Account account = new Account(13,"1234",9999.0,2);
        //修改的条数
        int num = sqlSession.insert("com.rw.mapper.AccountMapper.saveData", account);
        //手动提交mysql事物
        sqlSession.commit();

        sqlSession.close();
        logger.error("查询到的num是{}",num);

        Assert.assertTrue(num == 1);
    }

}
